package com.neusoft.work.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.work.dao.CustomerDao;
import com.neusoft.work.dao.HealthManagerCustomerDao;
import com.neusoft.work.po.Customer;
import com.neusoft.work.po.HealthManagerCustomer;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.service.HealthManagerCustomerService;

@Service
public class HealthManagerCustomerServiceImpl implements HealthManagerCustomerService {

    @Autowired
    private HealthManagerCustomerDao      hmcDao;

    @Autowired
    private CustomerDao                   customerDao;

    /**
     * 查询所有未分配管家的客户，分页 + 按名字模糊
     */
    @Override
    public PageResponseBean<List<Customer>> queryNoManager(
            String name, Long cur, Long number) {

        // 构造分页
        Page<Customer> page = new Page<>(cur, number);

        // 查询 wrapper：逻辑未删除 & 名字模糊（可选） & id 不在 hmc 表中
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq("isDeleted", false);
        if (name != null && !name.trim().isEmpty()) {
            qw.like("name", name.trim());
        }
        // 子查询：排除已经在 HealthManagerCustomer 中的 customerId
        qw.notInSql("id", "SELECT customerId FROM HealthManagerCustomer");

        // 执行分页查询
        Page<Customer> result = customerDao.selectPage(page, qw);

        // 封装返回
        PageResponseBean<List<Customer>> resp = new PageResponseBean<>();
        resp.setData(result.getRecords());
        resp.setTotal(result.getTotal());
        return resp;
    }

    // 原有 add/delete 方法省略...
    @Override
    public ResponseBean<Integer> add(HealthManagerCustomer record) {
        int rows = hmcDao.insert(record);
        if (rows > 0) {
            return new ResponseBean<>(record.getId());
        } else {
            return new ResponseBean<>(500, "新增失败");
        }
    }

    @Override
    public ResponseBean<Integer> removeAssignment(Integer managerId, Integer customerId) {
        int rows = hmcDao.delete(new QueryWrapper<HealthManagerCustomer>()
            .eq("healthManagerId", managerId)
            .eq("customerId", customerId)
        );
        if (rows > 0) {
            return new ResponseBean<>(customerId);
        } else {
            return new ResponseBean<>(500, "移除失败");
        }
    }
    
    @Override
    public ResponseBean<List<Map<String, Object>>> queryByManager(Integer managerId) {
        // 1. 先查出所有分配记录
        List<HealthManagerCustomer> relations = hmcDao.selectList(
            new QueryWrapper<HealthManagerCustomer>()
                .eq("healthManagerId", managerId)
        );

        // 2. 对每条关系，查 customer 并合并 assignTime
        List<Map<String,Object>> result = relations.stream().map(rel -> {
            Customer c = customerDao.selectById(rel.getCustomerId());
            // 使用 Spring 的 Bean 转 Map 或者自己手动组装
            Map<String, Object> m = new java.util.HashMap<>();
            m.put("id",            c.getId());
            m.put("name",          c.getName());
            m.put("type",          c.getType());
            m.put("gender",        c.getGender());
            m.put("age",           c.getAge());
            m.put("building",      c.getBuilding());
            m.put("roomNumber",    c.getRoomNumber());
            m.put("bedNumber",     c.getBedNumber());
            // … 如需更多字段可以继续 put …
            m.put("assignTime",    rel.getAssignTime());
            return m;
        }).collect(Collectors.toList());

        return new ResponseBean<>(result);
    }
}